var common = require("/resources/config/config.js");
var utils = require("/utils/util.js");
var commonMessages = require("/utils/messages.js");

//app.js
App({
  onLaunch: function () {

    var self=this;
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    var user = wx.getStorageSync('user') || {};
    var userInfo = wx.getStorageSync('userInfo') || {};

    if (!user.openid || ((user.expires_in || Date.now()) < (Date.now() + 60000))&&(!userInfo.nickName)){
      // 登录
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (res.code) {
            console.log(res.code);
            // 获取用户信息
            wx.getSetting({
              success: res => {
                if (res.authSetting['scope.userInfo']) {
                  wx.getUserInfo({
                    success: res => {
                      this.globalData.userInfo = res.userInfo
                      wx.setStorageSync('userInfo', res.userInfo)
                      if (this.userInfoReadyCallback) {
                        this.userInfoReadyCallback(res)
                      }
                    }
                  })
                }
              }
            });
            //get openid
            var d = self.globalData;//这里存储了appid、secret、token串    
            console.log(res.code);
            var url = common.getApiLink("getOpenid") + "?appId="+d.appid+"&code=" + res.code;
            utils.req_get(url, function (res) {
              console.log("openid=" + res.openid);
              user.openid=res.openid;
              user.expires_in=Date.now()+(res.expires_in*1000)
              

              //check user existance, if not then create user
              var urlCreateUser = common.getApiLink("createOrGetUser") + "?openId="+res.openid+"&isLoyalty=true";
              utils.req(urlCreateUser,null,function(resUser){
                console.log("user=" + resUser.name);
                user.name = resUser.name;
                user.id = resUser.id;
                self.globalData.user = user;
                wx.setStorageSync('user', user);
              });
            });
          }
        }
      })
    }
    else if(!user.id){
      var urlGetUser = common.getApiLink("readUserByOpenId") + "?openId=" + user.openid;
      utils.req_get(urlGetUser, function (resUser) {
        console.log("user=" + resUser.name);
        user.name = resUser.name;
        user.id = resUser.id;
        self.globalData.user = user;
        wx.setStorageSync('user', user);
      });
    }
  },
  globalData: {
    appid: 'wxccbb26b2d4c31458',  
    userInfo: wx.getStorageSync('userInfo'),
    user: wx.getStorageSync('user'),
    messages: commonMessages.messages.zh
  }
})

